package com.cy.wangly.rest.controller;

import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.Charset;

@RestController
@RequestMapping("/rest")
public class InputController {
    @PostMapping(value = "/input/body/{fileName}")
    public String execBody(@PathVariable String fileName, @RequestBody String body){
        return fileName;
    }

    @PostMapping(value = "/input/{fileName}")
    public String execInput(@PathVariable String fileName, HttpServletRequest request){
        getBodyString(request);
        return fileName;
    }


    /**
     * 获取请求Body
     * @param request 过滤后被的request
     * @return 返回body
     */
    public static void getBodyString(HttpServletRequest request) {
        File file = new File("E:\\firesoon\\log\\test.txt");
        OutputStreamWriter outWriter = null;
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            outWriter = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)));
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            char[] bytes = new char[1024];
            int b;
            while ((b=reader.read(bytes)) != -1) {
                outWriter.write(bytes,0,b);
            }
        } catch (Exception e) {
            throw new NullPointerException("获取requestBody出错：" + e.getMessage());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if(outWriter!=null){
                    outWriter.close();
                }
            } catch (IOException ignored) {
            }
        }
    }
}
